package com.quanyan.operative.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lefu.commons.utils.Page;
import com.quanyan.api.APIResponse;
import com.quanyan.common.http.HttpClientUtils;
import com.quanyan.common.utils.ObjectUtil;
import com.quanyan.mq.client.QcMsgClient;
import com.quanyan.mq.client.reqeust.MqRequestMsg;
import com.quanyan.operative.mapper.TbUserInfoMapper;
import com.quanyan.operative.model.req.ReqUserSetting;
import com.quanyan.operative.model.resp.TbUserInfo;
import com.quanyan.operative.service.TbUserInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/11/22.
 */
@Service
public class TbUserInfoServiceImpl implements TbUserInfoService {

    private static final Logger logger = LoggerFactory.getLogger(TbUserInfoServiceImpl.class);

    //c端接口地址
    @Value("${c.address}")
    private String address;

    //更新用户信息通知c端地址
    @Value("${c.setPlayerLabel}")
    private String setPlayerLabel;

    @Autowired
    private TbUserInfoMapper tbUserInfoMapper;

    @Resource(name = "qcMsgClient")
    private QcMsgClient qcMsgClient;

    @Override
    public APIResponse updateUserSetting(Integer pageIndex ,Integer pageSize){
        logger.info("开始更改pageIndex:{},pageSize:{},===================》{}",pageIndex,pageSize ,System.currentTimeMillis());
        try {
            Page page = new Page();
            page.setCurrentPage(pageIndex);
            page.setShowCount(pageSize);
            List<TbUserInfo> lst =  tbUserInfoMapper.findAllUser(page);
            for (TbUserInfo tbUserInfo : lst ){
                String userSetting = tbUserInfo.getUserSetting();
                if (userSetting != null && !userSetting.equals("")){
                    ReqUserSetting reqUserSetting = JSONObject.parseObject(userSetting, ReqUserSetting.class);
                    reqUserSetting.setIsDisturb(0);//0 未开启 关闭
                    tbUserInfo.setUserSetting(JSONObject.toJSONString(reqUserSetting));
                }
            }
            tbUserInfoMapper.batchUpdateUserSetting(lst);
            for (TbUserInfo tbUserInfo : lst ){
                MqRequestMsg mqRequestMsg = new MqRequestMsg();
                mqRequestMsg.setTopic(topic);
                mqRequestMsg.setTag(tag);
                mqRequestMsg.setBody(ObjectUtil.toByteArray(tbUserInfo));
                qcMsgClient.asyncSend(mqRequestMsg);
            }
            logger.info("更改设置成功===================》{}",System.currentTimeMillis());
            return APIResponse.returnSuccess(page.toString());
        } catch (Exception e) {
            logger.error("处理异常：{}",e);
            return APIResponse.returnFail(e.getMessage());
        }
    }



    @Async
    public int updateSetting(Integer currentUid,List<Integer> interests, Integer type, Integer state) {
        try{
            logger.info("开始回调C++接口");
            String url = address + setPlayerLabel;
            Map param = getJsonParam();
            param.put("currentUid",currentUid);
            if (type != null) {
                param.put("type",type);
            }
            if (state != null) {
                param.put("state",state);
            }
            if (interests != null) {
                param.put("interest_id",interests);

            }
            logger.info("接口地址：{},参数:{}",url,param.toString());
            String result = HttpClientUtils.postJson(url, JSON.toJSONString(param));
            logger.info("返回结果{}",result);
            JSONObject obj = JSON.parseObject(result);
            if(200 == (int) obj.get("errcode")){
                logger.error("c++更新用户资料回调成功：uid：【{}】,time：【{}】",currentUid,new Date());
                return 1;
            }
            else{
                logger.error("c++更新用户资料回调失败：uid：【{}】,time：【{}】",currentUid,new Date());
                return 2;
            }
        }catch (Exception e){
            logger.error("c++更新用户资料回调超时失败：uid：【{}】,time：【{}】,【{}】",currentUid,new Date(),e);
            return 3;

        }
    }

    private Map getJsonParam(){
        Map param = new HashMap<>();
        param.put("ver","1.0");
        param.put("protocol_ver",1);
        return param;
    }
}
